package com.example.aicloud.controller;

import com.alibaba.cloud.ai.tongyi.image.TongYiImagesOptions;
import com.baidubce.qianfan.Qianfan;
import com.baidubce.qianfan.model.chat.ChatResponse;
import com.baidubce.qianfan.model.image.Text2ImageResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.aicloud.common.ModelType;
import com.example.aicloud.common.Models;
import com.example.aicloud.entity.Answer;
import com.example.aicloud.service.IAnswerService;
import com.example.aicloud.utils.MinioUtil;
import com.example.aicloud.utils.Result;
import com.example.aicloud.utils.SecurityUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * 百度千帆大模型的操作
 * @author Mr.Tang
 * @date 2024-07-24
 */

@RestController
@RequestMapping("/qianfan")
public class QianfanController {

    @Value("${qianfan.api-key}")
    private String apiKey;

    @Value("${qianfan.secret-key}")
    private String secretKey;

    @Resource
    private IAnswerService answerService;

    @Resource
    private MinioUtil minioUtil;

    /**
     * 聊天功能
     */
    @RequestMapping("/chat")
    public Result chat(String question) {
        if (!StringUtils.hasLength(question)) {
            // 输入为空
            return Result.fail("请先输入内容!");
        }
        // 调用
        ChatResponse response = new Qianfan(apiKey, secretKey).chatCompletion()
                // 使用model指定预置模型
                .model("ERNIE-Speed-8K")
                // 添加用户消息 (此方法可以调用多次，以实现多轮对话的消息传递)
                .addMessage("user", question)
                // 发起请求
                .execute();
        String content = response.getResult();
        // 保存到数据库
        Answer answer = new Answer();
        answer.setTitle(question);
        answer.setContent(content);
        answer.setType(ModelType.CHAT.getType());
        answer.setModel(Models.QIANFAN.getModel());
        answer.setUid(SecurityUtil.getCurrentUser().getUid());
        boolean save = answerService.save(answer);
        if (!save) {
            return Result.fail("服务器睡着了, 请重试");
        }
        // 返回
        return Result.success(content);
    }

    /**
     * 绘画
     * @param question
     * @return
     */
    @RequestMapping("/draw")
    public Result draw(String question) {
        if (!StringUtils.hasLength(question)) {
            return Result.fail("请输入问题");
        }
        // 调用接口
        Text2ImageResponse response = new Qianfan(apiKey, secretKey)
                .text2Image()
                .prompt(question)
                .execute();
        byte[] image = response.getData().get(0).getImage();
        // 把流转换并保存到minio里面
        String url = "";
        String fileName = "qf-" + UUID.randomUUID().toString().replace("-", "");
        try(ByteArrayInputStream inputStream = new ByteArrayInputStream(image)) {
            url = minioUtil.upload(fileName, inputStream, "image/png");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 把图片地址保存到数据库里面
        Answer answer = new Answer();
        answer.setTitle(question);
        answer.setContent(url);
        answer.setType(ModelType.DRAW.getType());
        answer.setModel(Models.QIANFAN.getModel());
        answer.setUid(SecurityUtil.getCurrentUser().getUid());
        boolean save = answerService.save(answer);
        if (!save) {
            return Result.fail("服务器睡着了, 请重试");
        }
        // 返回
        return Result.success(url);
    }


    /**
     * 获取聊天历史列表
     * @return
     */
    @RequestMapping("/getchatlist")
    public Result getChatList() {
        long uid = SecurityUtil.getCurrentUser().getUid();
        // 查询历史信息
        QueryWrapper<Answer> wrapper = new QueryWrapper<>();
        wrapper.eq("uid", uid);
        wrapper.eq("type", ModelType.CHAT.getType());
        wrapper.eq("model", Models.QIANFAN.getModel());
        wrapper.orderByDesc("aid");
        List<Answer> list = answerService.list(wrapper);
        // 返回
        return Result.success(list);
    }


    /**
     * 获取绘图历史信息
     * @return
     */
    @RequestMapping("/getdrawlist")
    public Result getDrawList() {
        long uid = SecurityUtil.getCurrentUser().getUid();
        // 查询历史信息
        QueryWrapper<Answer> wrapper = new QueryWrapper<>();
        wrapper.eq("uid", uid);
        wrapper.eq("type", ModelType.DRAW.getType());
        wrapper.eq("model", Models.QIANFAN.getModel());
        wrapper.orderByDesc("aid");
        List<Answer> list = answerService.list(wrapper);
        // 返回
        return Result.success(list);
    }

}
